package org.zero.service;

import java.io.IOException;
import java.net.Socket;
import java.util.Random;

import org.zero.dao.UserOperator;
import org.zero.entity.Request;
import org.zero.entity.Response;
import org.zero.entity.User;
import org.zero.view.ServerWindow;

public class RegisterService implements ServerService {

	public void service(Request request, Socket socket, ServerWindow serverWindow) throws IOException {
		UserOperator userOperator = new UserOperator();

		User user = request.getFromUser();

		// 获取 IP 和 端口
		String ip = socket.getInetAddress().getHostAddress();
		int port = socket.getPort();
		serverWindow.println("用户（" + ip + ":" + port + "）正在尝试注册...\n");

		// 生成随机 QQ 号
		String id = null;
		do {
			StringBuffer stringBuffer = new StringBuffer();
			Random random = new Random();
			for (int i = 1; i <= 6; i++) {
				int num = random.nextInt(10);
				// 保证第一位不为0
				if (i == 1) {
					while (num == 0) {
						num = random.nextInt(10);
					}
				}
				stringBuffer.append(num);
			}
			id = stringBuffer.toString();
			if (userOperator.getUserById(id) == null) {
				break;
			}
		} while (true);

		// 完善 user 封装信息
		user.setId(id);
		user.setIp(ip);
		user.setPort(port);

		Response response = new Response();
		response.setResponseServiceName(request.getRequestServiceName());

		if (userOperator.saveUser(user)) {
			response.setResponseCode(Response.REGISTER_SUCCESS);
			response.setMessage("注册成功！！！");
			response.setToUser(user);
			serverWindow.println("用户【" + user.getName() + "-" + user.getNickname() + "-" + user.getId() + "】注册成功！\n");
			send(socket, response);
			return;
		}

		response.setResponseCode(Response.REGISTER_FAIL);
		response.setMessage("注册失败！！！");
		serverWindow.println("用户【" + user.getId() + "】注册失败！\n");
		send(socket, response);
	}

}
